package main

import (
	"flag"
	"fmt"
	"strings"

	"github.com/layidao/utilx"
)

func main() {
	var (
		input, output  string
		startKW, endKW string
		cutset         string
		size           int
	)

	flag.StringVar(&input, "i", "", "需要处理的文件")
	flag.StringVar(&output, "o", "", "输出文件路径")
	flag.StringVar(&startKW, "start", "", "开始标记")
	flag.StringVar(&endKW, "end", "", "结束标记")
	flag.StringVar(&cutset, "cutset", "", "trim字符串")

	flag.Parse()

	if input == "" || output == "" || startKW == "" || endKW == "" {
		fmt.Println("go run main.go -i=a -o=b -start=aaa -end=bbb")
		return
	}

	fmt.Println(input, output)

	content, err := getContentByKeyword(input, startKW, endKW)
	if err != nil {
		fmt.Println(err)
		return
	}
	content = strings.TrimSpace(content)
	content = strings.Trim(content, cutset)

	size, err = utilx.FilePutContent(output, content)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Printf("成功向%s写入%d字节\n", output, size)
}

func getContentByKeyword(filePath, start, end string) (content string, err error) {

	content, err = utilx.FileGetContent(filePath)
	if err != nil {
		return
	}

	startIndex := strings.Index(content, start)
	if startIndex == -1 {
		startIndex = 0
	} else {
		startIndex += len(start)
	}

	endIndex := strings.Index(content, end)
	if endIndex == -1 {
		endIndex = len(content)
	}

	content = content[startIndex:endIndex]

	return
}
